﻿using System;
using System.Drawing;
using System.Windows.Forms;

namespace Common
{
    public class LayoutHelper
    {
        public delegate Control CreateControl(int x, int y);

        public static void CreateControlsToFillClientArea(Form form, Size size, CreateControl createControl)
        {
            Size buttonSize = new Size(form.ClientRectangle.Width / size.Width, form.ClientRectangle.Height / size.Height);
            Size buttonSpace = new Size(form.ClientRectangle.Width % size.Width, form.ClientRectangle.Height % size.Height);

            Rectangle rect = new Rectangle(new Point(0, 0), buttonSize);
            for (int y = 0; y < size.Height; y++)
            {
                int spaceX = buttonSpace.Width;
                for (int x = 0; x < size.Width; x++)
                {
                    Control control = createControl(x, y);
                    form.Controls.Add(control);
                    control.Location = rect.Location;
                    control.Size = rect.Size;

                    int offsetX = buttonSize.Width;
                    if (spaceX > 0)
                    {
                        offsetX++;
                        spaceX--;
                    }
                    rect.Offset(offsetX, 0);
                }

                int offsetY = buttonSize.Height;
                if (buttonSpace.Height > 0)
                {
                    offsetY++;
                    buttonSpace.Height--;
                }
                rect.Offset(-rect.Location.X, offsetY);
            }
        }
    }
}
